package cn.itrip.biz.service.impl;

import cn.itrip.beans.dto.Dto;
import cn.itrip.beans.pojo.*;
import cn.itrip.beans.vo.*;
import cn.itrip.biz.service.QueryHotelInfoService;
import cn.itrip.common.DtoUtils;
import cn.itrip.common.RedisUtil;
import cn.itrip.dao.mapper.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;


@Service
public class QueryHotelInfoServiceImpl implements QueryHotelInfoService {
    @Resource
    private ItripCommentMapper itripCommentMapper;
    @Resource
    private ItripHotelRoomMapper itripHotelRoomMapper;
    @Resource
    private ItripLabelDicMapper itripLabelDicMapper;
    @Resource
    private ItripImageMapper itripImageMapper;
    @Resource
    private ItripHotelMapper itripHotelMapper;
    @Resource
    private ItripHotelOrderMapper itripHotelOrderMapper;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private ItripHotelTempStoreMapper itripHotelTempStoreMapper;
    @Resource
    private ItripUserLinkUserMapper itripUserLinkUserMapper;
    @Resource
    private ItripOrderLinkUserMapper itripOrderLinkUserMapper;

    @Override
    public Dto getCommentList(QueryComment queryComment) throws Exception {
        ItripCommentPage itripCommentPage = new ItripCommentPage();
        long count = itripCommentMapper.selectCommentCount(queryComment);
        long size = queryComment.getPageSize();
        long curPage = count%size==0?count/size:count/size+1;
        itripCommentPage.setTotal(count);
        itripCommentPage.setPageCount(curPage);
        itripCommentPage.setCurPage(queryComment.getPageNo());
        itripCommentPage.setBeginPos((queryComment.getPageNo()-1)*size);
        itripCommentPage.setPageSize(size);
        itripCommentPage.setQuery(queryComment);
        itripCommentPage.setLimitone((queryComment.getPageNo()-1)*size);
        List<ItripComment> itripComments = itripCommentMapper.selectCommentList(itripCommentPage);
        itripCommentPage.setRows(itripComments);
        return DtoUtils.getDto("100", "评论列表", itripCommentPage, "true", null);

    }

    @Override
    public Dto getHotelScore(String id) throws Exception {
        HotelScore hotelScore = itripCommentMapper.getHotelScore(Long.parseLong(id));
        return DtoUtils.getDto("100", "评分列表", hotelScore, "true", null);
    }

    @Override
    public Dto queryHotelRoombed() throws Exception {
        List<ItripLabelDic> ild = itripLabelDicMapper.selectHotelRoombed();
        return DtoUtils.getDto("10","床型列表",ild,"true",null);
    }

    @Override
    public Dto getTravelType() throws Exception {
        List<ItripLabelDic> tt = itripLabelDicMapper.selectTravelType();
        return DtoUtils.getDto("10","获取旅游类型列表成功",tt,"true",null);
    }

    @Override
    public Dto getImg(String id) throws Exception {
        if (null != id && "" != id) {
            List<ItripImage> imgList = itripImageMapper.selectImg(Long.parseLong(id));
            return DtoUtils.getDto("0", "获取酒店图片成功", imgList, "true", null);
        }
        return DtoUtils.getDto("10005", "获取酒店图片失败", "", "false", null);
    }

    @Override
    public Dto getCount(String id) throws Exception {
        if (null != id) {
            long havingimg = itripCommentMapper.getIsHavingImg(Long.parseLong(id));
            long improve = itripCommentMapper.getisOkNO(Long.parseLong(id));
            long isOk = itripCommentMapper.getisOkYES(Long.parseLong(id));
            long allCount = itripCommentMapper.getAllCount(Long.parseLong(id));
            ItripCommentVo itripCommentVo = new ItripCommentVo();
            itripCommentVo.setIsok(isOk);
            itripCommentVo.setAllcomment(allCount);
            itripCommentVo.setHavingimg(havingimg);
            itripCommentVo.setImprove(improve);
            return DtoUtils.getDto("0", "评论数量", itripCommentVo, "true", null);
        }
        return DtoUtils.getDto("0", "id不能为空", "", "false", null);
    }

    @Override
    public Dto queryHotelDetails(String id)throws Exception{

        ItripHotel itripHotel = itripHotelMapper.queryHotelDetails(Long.parseLong(id));
        ItripLabelDic itripLabelDic=new ItripLabelDic();

        itripLabelDic.setDescription(itripHotel.getDetails());
        List<ItripLabelDic> list= itripLabelDicMapper.selectDesc(Long.parseLong(id));
        list.add(0, itripLabelDic);

        return DtoUtils.getDto("0", "酒店描述", list, "true", null);
    }

    @Override
    public Dto queryHotelFacilities(String id)throws Exception {
        ItripHotel itripHotel = itripHotelMapper.queryHotelFacilities(Long.parseLong(id));
        return DtoUtils.getDto("0", "酒店设施", itripHotel.getFacilities(), "true", null);
    }

    @Override
    public Dto queryHotelPolicy(String id) throws Exception{
        ItripHotel itripHotel = itripHotelMapper.queryHotelPolicy(Long.parseLong(id));
        return DtoUtils.getDto("0", "酒店政策", itripHotel.getHotelPolicy(), "true", null);
    }

    @Override
    public Dto getCommentImg(String id) throws Exception {
        List<ItripImage> itripImage = itripCommentMapper.getCommentImg(Long.parseLong(id));
        return DtoUtils.getDto("0", "酒店评论图片", itripImage, "true", null);
    }

    @Override
    public Dto getHotelDesc(String id) throws Exception {
        ItripHotel itripHotel= itripHotelMapper.selectById(Long.parseLong(id));

        if(null!=itripHotel){
            return DtoUtils.getSuccesDto(itripHotel);
        }
        return DtoUtils.getSuccesDto(itripHotel);
    }

    @Override
    public Dto queryVideoDesc(String id) throws Exception {
        ItripHotel itripHotel=itripHotelMapper.queryHotelDetails(Long.parseLong(id));
        if(null!=itripHotel){
            return DtoUtils.getSuccesDto(itripHotel);
        }
        return DtoUtils.getSuccesDto(itripHotel);
    }

    @Override
    public Dto selectByQuery(ItripHotelRoom itripHotelRoom) throws Exception {
        List<ItripHotelRoom> itripHotelRooms = itripCommentMapper.selectByQuery(itripHotelRoom);
        List data = new ArrayList();
        for (ItripHotelRoom itripHotelRoom1: itripHotelRooms) {
            List list = new ArrayList();
            list.add(itripHotelRoom1);
            data.add(list);
        }
        return DtoUtils.getDto("0", "酒店房间",data, "true", null);
    }

    @Override
    public Dto getHotelRoomImg(String id) throws Exception {
        if (null != id && "" != id) {
            List<ItripImage> imgList = itripImageMapper.getHotelRoomImg(Long.parseLong(id));
            return DtoUtils.getDto("0", "获取酒店评论图片", imgList, "true", null);
        }
        return DtoUtils.getDto("10005", "获取酒店评论图片失败", "", "false", null);
    }

    @Override
    public Dto getPreorder(ItripHotelOrder itripHotelOrder) throws Exception {

        OrderData orderData=new OrderData();//返回的订单数据
        //订单表（房间roomId） 酒店房间表（房间id）
        ItripHotelRoom itripHotelRoom=itripHotelRoomMapper.selectByPrimaryKey(itripHotelOrder.getRoomId());
        // 酒店房间表（房间id）房间实时库存表(房间roomId） 获取房间实时库存数据
        ItripHotelTempStore itripHotelTempStore=itripHotelTempStoreMapper.selectTempStore(itripHotelRoom.getId());

        String uuid = UUID.randomUUID().toString();
        uuid=uuid.replaceAll("-", "");
        //获取订单最大数加1
        orderData.setId(Long.parseLong(String.valueOf(itripHotelOrderMapper.selectBigId()+1)));
        orderData.setOrderNo(uuid);//生成的订单号
        orderData.setPrice(itripHotelRoom.getRoomPrice());//住房价格
        orderData.setStore(itripHotelTempStore.getStore());//房间库存数
        orderData.setOrderNo(uuid);//生成的订单号
        orderData.setPrice(itripHotelRoom.getRoomPrice());//住房价格
        orderData.setStore(itripHotelTempStore.getStore());//房间库存数
        return DtoUtils.getSuccesDto(orderData);

    }

    @Override
    public Dto addhotelorder(ItripHotelOrder itripHotelOrder,String token) throws Exception {

        String to= redisUtil.getValue(token);
        Map map = (Map) JSON.parse(to);
        ItripHotelRoom itripHotelRoom=itripHotelRoomMapper.selectByPrimaryKey(itripHotelOrder.getRoomId());
        itripHotelOrder.setUserId(Long.parseLong(""+map.get("id")));

        String uuid = UUID.randomUUID().toString();
        uuid=uuid.replaceAll("-", "");
        itripHotelOrder.setOrderNo(uuid);//生成的订单号
        itripHotelOrder.setId(Long.parseLong(String.valueOf(itripHotelOrderMapper.selectBigId()+1)));

        //计算总价
        BigDecimal total = new BigDecimal(itripHotelOrder.getCount());
        itripHotelOrder.setPayAmount(itripHotelRoom.getRoomPrice().multiply(total));

        //计算时间差
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(itripHotelOrder.getCheckOutDate());
        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(itripHotelOrder.getCheckInDate());
        itripHotelOrder.setBookingDays(cal1.get(Calendar.DAY_OF_YEAR)-cal2.get(Calendar.DAY_OF_YEAR));
        //设值
        itripHotelOrder.setOrderStatus(0);//订单状态
        itripHotelOrder.setBookType(0);
        itripHotelOrder.setCreationDate(new Date());
        //获取酒店名称
        ItripHotel itripHotel = itripHotelMapper.selectById(itripHotelOrder.getHotelId());
        itripHotelOrder.setHotelName(itripHotel.getHotelName());
        itripHotelOrder.setCreatedBy(Long.parseLong(map.get("id").toString()));
        String linkname="";//定义房客对象
        for (ItripUserLinkUser linkUser:itripHotelOrder.getLinkUser()){
            //获取用户联系人信息
            linkUser=itripUserLinkUserMapper.selectByPrimaryKey(linkUser.getId());
            //将获取的用户联系人信息给订单联系人
            ItripOrderLinkUser itripOrderLinkUser=new ItripOrderLinkUser();
            itripOrderLinkUser.setCreatedBy(linkUser.getCreatedBy());//创建者
            itripOrderLinkUser.setCreationDate(new Date());//创建时间
            itripOrderLinkUser.setLinkUserId(linkUser.getUserId());//联系人id
            itripOrderLinkUser.setLinkUserName(linkUser.getLinkUserName());//联系人姓名
            itripOrderLinkUser.setOrderId(itripHotelOrder.getId());//订单id
            //添加订单联系人信息
            itripOrderLinkUserMapper.insertSelective(itripOrderLinkUser);
            linkname+=linkUser.getLinkUserName();
        }
        itripHotelOrder.setLinkUserName(linkname);
        //添加酒店订单


        try {
            int  order = itripHotelOrderMapper.insertSelective(itripHotelOrder);
            if(order>0){
                //修改库存
                int up = itripHotelTempStoreMapper.updatestoreByid(itripHotelOrder.getHotelId());
                if(up>0){
                    DtoUtils.getSuccesDto("修改成功");
                }
            }
        } catch (Exception e) {
            DtoUtils.getExcetpionDto(e,"");
        }

        return DtoUtils.getSuccesDto(itripHotelOrder);
    }

    @Override
    public Dto queryOrderById(String orderid) {
        return null;
    }


    @Override
    public Dto addComment(CommentVo commentVo, HttpServletRequest request) throws Exception {
        String token=request.getHeader("token");
        //根据获取的key获取redis中对应的value
        String key=redisUtil.getValue(token);
        //把JSON转换成ItripUser对象
        ItripUser user= JSONObject.parseObject(key,ItripUser.class);
        //获取id
        long id = user.getId();
        commentVo.setId(id);
        //获取总体评价
        long score = commentVo.getFacilitiesScore()+commentVo.getHygieneScore()+commentVo.getPositionScore()+commentVo.getServiceScore();
        //设置总体评价
        commentVo.setScore(score/4==0?score/4:score/4+score%4);
        //添加点评
        int add = itripCommentMapper.insert(commentVo);
        //获取订单id
        long commentID = itripCommentMapper.getCommentID();
        String path = request.getSession().getServletContext().getRealPath("/data1/uploadimg/comment");
        if (0<add && 0<commentVo.getItripImages().size()) {
            int i = 1;
            for (Object imgurl: commentVo.getItripImages()) {
                ItripImage itripImage = new ItripImage();
                String url = imgurl.toString();
                url = url.substring(8);
                url = url.substring(0,url.length()-1);
                itripImage.setImgUrl(path+"\\"+url);
                itripImage.setCreatedBy(id);
                itripImage.setType("2");
                itripImage.setPosition(i);
                itripImage.setTargetId(commentID);
                itripImageMapper.insert(itripImage);
                i++;
            }
        }
        long results = itripHotelOrderMapper.updateOrderStatus(commentVo.getOrderId());
        if (results!=0) {
            return DtoUtils.getDto("0", "点评成功", null, "true", null);
        }
        return DtoUtils.getDto("0", "点评失败", null, "true", null);
    }


}
